package org.vehicle.iface;

import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.vehicle.common.MyConstant;
import org.vehicle.entity.ManagerInfo;
import org.vehicle.service.ManagerInfoService;
import org.vehicle.service.redis.RedisService;
import org.vehicle.util.JsonUtils;
import org.vehicle.util.MD5Util;
import org.vehicle.vo.DeviceLoginVO;

@Controller
@RequestMapping("interface/deviceLogin")
public class DeviceLoginController {
	
	private static Logger logger = LogManager.getLogger(DeviceLoginController.class.getName());
	
	@Autowired
	private RedisService redisService;
	@Autowired
	private ManagerInfoService managerInfoService;
	
	/**
	 * 设备登录
	 * @param deviceLoginVO
	 * @return
	 */
	@RequestMapping("login")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> login(@RequestBody DeviceLoginVO deviceLoginVO){
		logger.trace(deviceLoginVO.toString());
		Map<String, Object> retMap=new HashMap<String, Object>();
		retMap.put("state", 0);
		retMap.put("token", null);
		try{
			ManagerInfo managerInfo=managerInfoService.findManagerInfoByLoginName(deviceLoginVO.getLoginName());
			if(managerInfo==null){
				retMap.put("msg", "用户名不存在");
			}else{
				if(managerInfo.getPassword().equals(deviceLoginVO.getPassword())){
					if(managerInfo.getManagerType()==MyConstant.MANAGER_TYPE_USER){
						String md5Str=MD5Util.MD5(managerInfo.getLoginName()+managerInfo.getManagerName()+managerInfo.getPassword());
						String token=Base64Utils.encodeToString((managerInfo.getCreateDate().getTime()+md5Str).getBytes());		
						redisService.setString(token, JsonUtils.toJson(managerInfo));
						retMap.put("state", 1);
						retMap.put("msg", "登录成功");
						retMap.put("token", token);
					}else{
						retMap.put("msg", "无登录权限");
					}
				}else{
					retMap.put("msg", "用户名密码不正确");
				}
			}
		}catch(Exception e){
			logger.error(e);
			retMap.put("msg", "系统异常");
		}
		return new ResponseEntity<Map<String,Object>>(retMap, HttpStatus.OK);
	}
	
}
